<template>
  <div class="main-container" v-loading="loading" element-loading-text="努力加载中...">
    <div class="content-container">
      <div class="title-container">
        <div class="title-text">呼吸</div>
      </div>
      <div class="subtitle-container">
        <el-text class="subtitle-text">AHI:</el-text>
      </div>
      <div class="charts-wrapper">
        <div class="chart-container chart-background-white">
          <div class="chart-content">
            <el-text class="ahi-title">AHI指数：{{ ahiValue }}</el-text>
            <div class="indicator-wrapper">
              <div class="indicator-bar">
                <div class="indicator-segment normal">正常</div>
                <div class="indicator-segment mild">轻度</div>
                <div class="indicator-segment moderate">中度</div>
                <div class="indicator-segment severe">重度</div>
              </div>
              <!-- 指示器 -->
              <div :style="indicatorStyle" class="indicator">
                ▲
              </div>
            </div>
            <el-text class="ahi-suggestion">保持合理饮食和适度运动有助于健康水平</el-text>
          </div>
        </div>
        <div class="chart-container chart-background-f4efeb">
          <div class="info-container">
            <div class="info-title">什么是AHI：</div>
            <div class="info-content">
              AHI指数是指每小时睡眠内呼吸暂停加上低通气的总次数。
              <br>
              AH分度参考：
              <br>
              AHI<5：正常;
              <br>
              5<=AHI<16：轻度睡眠呼吸暂停低通气综合征;
              <br>
              16<=AHI<=30：中度睡眠呼吸暂停低通气综合征;
              <br>
              30>AH：重度睡眠呼吸暂停低通气综合征;
            </div>
          </div>
        </div>
      </div>
      <div class="subtitle-container">
        <el-text class="subtitle-text">呼吸分类图（显示每分钟是否存在呼吸紊乱）:</el-text>
      </div>
      <div class="chart-large-container">
        <div id="breathStopChart" class="chart-large"></div>
      </div>

      <!-- 血氧时分图 -->
      <div class="subtitle-container" v-if="isOxygenDataLoaded">
        <el-text class="subtitle-text">血氧分时图：</el-text>
      </div>
      <div class="chart-containerOX" v-if="isOxygenDataLoaded">
        <div id="OXTSChart" class="chart-large"></div>
        <div class="stats-container">
          <div class="stat-item " :class="getStatusClass(minOxygen)">
            <el-text class="stat-title">最低血氧</el-text>
            <el-text class="stat-value min-oxygen-value">{{minOxygen}}%</el-text>
          </div>
          <div class="stat-item max-oxygen-box" :class="getStatusClass(maxOxygen)">
            <el-text class="stat-title">最高血氧</el-text>
            <el-text class="stat-value max-oxygen-value">{{ maxOxygen }}%</el-text>
          </div>
          <div class="stat-item avg-oxygen-box" :class="getStatusClass(avgOxygen)">
            <el-text class="stat-title">平均血氧</el-text>
            <el-text class="stat-value avg-oxygen-value">{{ avgOxygen }}%</el-text>
          </div>
        </div>
      </div>

      <div class="evaluation-wrapper">
        <div class="evaluation-content">
          <div class="evaluation-header">
            <div class="icon">
              <font-awesome-icon :icon="['fas','fa-file-alt']" size="2x" class="icon-color"></font-awesome-icon>
            </div>
            <div class="evaluation-title">呼吸评估结果：</div>
            <el-button v-if="enableEdit" class="edit-button" @click="showEditInput">
              <font-awesome-icon :icon="['fas','fa-pencil-alt']" class="edit-icon"></font-awesome-icon>
              <el-text class="edit-text">编辑</el-text>
            </el-button>
          </div>
          <div class="evaluation-body">
            <el-input type="textarea" class="evaluation-input" v-model="currentUserBreathData.evaluation" v-if="editMode"></el-input>
            <el-text v-else :span="24" class="evaluation-display">
              {{ currentUserBreathData.evaluation }}
            </el-text>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script setup>
import StatusType from "@/components/StatusType.vue";
import {FontAwesomeIcon} from "@fortawesome/vue-fontawesome";
import '@/assets/css/reportCard.css';
import breathStopImg from '@/assets/img/1.png'
import slowBreathImg from '@/assets/img/4.png'
import AHIImg from '@/assets/img/2.png'
import {ref, onMounted, onUnmounted, reactive, watch, computed, markRaw} from "vue";
import * as echarts from "echarts";
import sleepData from "@/api/sleepData.js";
import {ElMessage} from "element-plus";

const isOxygenDataLoaded = ref(false); // 标记血氧数据是否加载完成
const loading = ref(false); // 加载状态

onMounted(() => {
  console.log("mounted");
  loadOxygenData(props.currentReportId);
  getBreathData(props.currentReportId);
  // 监听窗口大小变化
  window.addEventListener('resize', resizeCharts);
});

onUnmounted(() => {
  console.log("unmounted");
  if (currentUserBreathData.value.evaluation !== evaluationBackup.value) {
    const updateBreathDataDto = {
      reportId: props.currentReportId,
      evaluation: currentUserBreathData.value.evaluation
    };
    sleepData.updateBreatheEvaluate(updateBreathDataDto).then((res) => {
      if (res.data.code === 200) {
        // 更新成功
      }
    }).catch((err) => {
      console.log(err);
    });
  }
  disposeChart();
});

const props = defineProps({
  currentReportId: Number,
  enableEdit: Boolean
});

watch(() => props.currentReportId, (newId) => {
  getBreathData(newId);
  loadOxygenData(newId);
});

watch(() => props.enableEdit, (newValue) => {
  enableEdit.value = newValue;
});

const enableEdit = ref(props.enableEdit);
const evaluationBackup = ref('');
const getBreathData = (reportId) => {
  loading.value = true;
  sleepData.getBreatheData(reportId).then((res) => {
    const breatheStop = res.data.data.breatheStop;
    if (breatheStop != null) {
      breathStopData.value.count = breatheStop.total;
      breathStopData.value.time = breatheStop.maxDurationTime;
      breathStopData.value.rate = breatheStop.perHour;
      slowBreathData.value.count = breatheStop.total;
      slowBreathData.value.time = breatheStop.maxDurationTime;
      slowBreathData.value.rate = breatheStop.perHour;
    }
    ahiValue.value = res.data.data.ahi;
    currentUserBreathData.value = res.data.data;
    evaluationBackup.value = currentUserBreathData.value.evaluation;
    createBreathStopChart(res.data.data.breatheStopTime);
  }).catch((err) => {
    console.log(err);
  }).finally(() => {
    loading.value = false;
  });
};

const saveOxygenData = (data) => {
  const cache = {
    data,
    timestamp: new Date().getTime(), // 当前时间戳
  };
  localStorage.setItem('oxygenData', JSON.stringify(cache));
};

const loadOxygenData = (reportId) => {
  const cachedData = JSON.parse(localStorage.getItem('oxygenData'));
  console.log(cachedData);
  if (cachedData) {
    const now = new Date().getTime();
    const cacheDuration = 5 * 60 * 1000; // 5 分钟（单位：毫秒）
    if (now - cachedData.timestamp < cacheDuration) {
      // 缓存未过期，使用缓存数据
      createOXTSChart(cachedData.data);
      const oxygenValues = cachedData.data.oxygenValues.map(value => value * 100);
      minOxygen.value = Math.min(...oxygenValues).toFixed(1);
      maxOxygen.value = Math.max(...oxygenValues).toFixed(1);
      avgOxygen.value = (oxygenValues.reduce((sum, value) => sum + value, 0) / oxygenValues.length).toFixed(1);
      isOxygenDataLoaded.value = true; // 标记数据加载完成
    } else {
      // 缓存过期，清除缓存并重新加载
      localStorage.removeItem('oxygenData');
      getOxygenDate(reportId); // 使用传入的 reportId
    }
  } else {
    // 如果没有缓存数据，重新加载
    getOxygenDate(reportId); // 使用传入的 reportId
  }
};

const minOxygen = ref(0); // 最低血氧
const maxOxygen = ref(0); // 最高血氧
const avgOxygen = ref(0); // 平均血氧

const getOxygenDate = (reportId) => {
  loading.value = true;
  sleepData.getOxygenDate(reportId).then((res) => {
    const oxygenData = res.data.data;
    createOXTSChart(oxygenData);

    // 保存血氧数据到 LocalStorage（带时间戳）
    saveOxygenData(oxygenData);

    // 计算最低、最高和平均血氧
    const oxygenValues = oxygenData.oxygenValues.map(value => value * 100); // 转换为百分比
    minOxygen.value = Math.min(...oxygenValues).toFixed(1); // 最低血氧
    maxOxygen.value = Math.max(...oxygenValues).toFixed(1); // 最高血氧
    avgOxygen.value = (oxygenValues.reduce((sum, value) => sum + value, 0) / oxygenValues.length).toFixed(1); // 平均血氧
    isOxygenDataLoaded.value = true; // 标记数据加载完成
  }).catch((err) => {
    console.log(err);
    isOxygenDataLoaded.value = false; // 标记数据加载失败
  }).finally(() => {
    loading.value = fa +lse; // 使用箭头函数包装
  });
};

const getStatusClass = (oxygenValue) => {
  if (oxygenValue >= 90) {
    return 'stat-good'; // 血氧正常
  } else if (oxygenValue >= 80 && oxygenValue < 90) {
    return 'stat-warning'; // 血氧偏低
  } else {
    return 'stat-danger'; // 血氧过低
  }
};

// 图表创建
const breathStopChartInstance = ref(null);
const OXTSChartInstance = ref(null);
const createBreathStopChart = (breatheStopTime) => {
  breathStopChartInstance.value = markRaw(echarts.init(
      document.getElementById("breathStopChart")
  ));
  const times = breatheStopTime.breathStopLabel.map((_, index) => {
    const date = new Date(breatheStopTime.startTime + index * breatheStopTime.frequency);
    const hours = date.getHours().toString().padStart(2, '0');
    const minutes = date.getMinutes().toString().padStart(2, '0');
    return `${hours}:${minutes}`;
  });
  // 去重处理，使得横坐标只显示到分钟
  const uniqueTimes = Array.from(new Set(times));
  breathStopChartInstance.value.setOption({
    grid: {
      left: '5%',
      right: '5%',
      top: '10%',
      bottom: '5%',
      containLabel: true,
    },
    xAxis: {
      type: 'category',
      data: times,
    },
    yAxis: {
      type: 'category',
      data: ['正常', '紊乱'],
      axisLabel: {
        formatter: function (value) {
          return value;
        }
      }
    },
    series: [{
      type: 'line',
      data: breatheStopTime.breathStopLabel.map((label, index) => ({
        value: [times[index], label === 1 ? '正常' : '紊乱'],
      })),
      step: 'start',
      lineStyle: {
        width: 2,
      },
      symbolSize: 8,
      symbol: 'none', // 隐藏圆点
    }],
    tooltip: {
      trigger: 'axis',
      formatter: function (params) {
        let tooltipText = '';
        params.forEach(param => {
          tooltipText += `时间: ${param.name}<br/>状态: ${param.value[1]}<br/>`;
        });
        return tooltipText;
      }
    },
  });
};

const createOXTSChart = (oxygenData) => {
  const { startTime, frequency, oxygenValues: rawOxygenValues } = oxygenData;

  // 将原始数据（0.956）转换为百分比形式（95.6）
  const oxygenValues = rawOxygenValues.map(value => value * 100);

  // 生成时间轴
  const times = oxygenValues.map((_, index) => {
    const date = new Date(startTime + index * 1000);
    const hours = date.getHours().toString().padStart(2, '0');
    const minutes = date.getMinutes().toString().padStart(2, '0');
    return `${hours}:${minutes}`;
  });

  // 初始化 ECharts 实例
  OXTSChartInstance.value = markRaw(echarts.init(document.getElementById("OXTSChart"), "purple-passion"));

  // 设置图表配置
  OXTSChartInstance.value.setOption({
    grid: {
      left: '5%',
      right: '5%',
      top: '20%', // 调整顶部间距，为图例留出空间
      bottom: '10%',
      containLabel: true,
    },
    xAxis: {
      type: 'category',
      data: times,
      axisLabel: {
        formatter: function (value) {
          return value; // 直接返回格式化后的时间
        }
      }
    },
    yAxis: {
      type: 'value',
      min: 75, // 最小值为 75%
      max: 100, // 最大值为 100%
      interval: 5, // 刻度间隔为 5%
      axisLabel: {
        formatter: function (value) {
          return `${value}%`; // 将 Y 轴的值显示为百分比
        }
      }
    },
    visualMap: {
      show: true, // 显示 visualMap 组件
      pieces: [
        {
          gt: 90, // 大于 90%
          lte: 100, // 小于等于 100%
          color: '#1E90FF', // 蓝色
          label: '血氧 > 90%' // 图例名称
        },
        {
          gt: 0, // 大于 0%
          lte: 90, // 小于等于 90%
          color: '#FFA500', // 橙色
          label: '血氧 ≤ 90%' // 图例名称
        }
      ],
      orient: 'horizontal', // 水平显示
      left: 'center', // 居中显示
      top: '5%', // 将图例放在图表顶部
      textStyle: {
        color: '#333', // 文字颜色
        fontSize: 12 // 文字大小
      }
    },
    series: [
      {
        name: '血氧',
        type: 'line',
        data: oxygenValues,
        symbol: 'none', // 去掉折线图中的点
        lineStyle: {
          width: 2, // 设置折线宽度为2
        },
        areaStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              {
                offset: 0,
                color: 'rgba(30, 144, 255, 0.1)', // 蓝色区域填充
              },
              {
                offset: 1,
                color: 'rgba(255, 165, 0, 0.1)', // 橙色区域填充
              },
            ],
          },
        },
        smooth: false, // 平滑曲线
      },
    ],
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross'
      },
      formatter: function (params) {
        const date = new Date(startTime + params[0].dataIndex * 1000);
        const time = `${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
        return `时间: ${time}<br/>血氧: ${params[0].value.toFixed(1)}%`; // 显示一位小数
      }
    },
    dataZoom: [
      {
        type: 'slider', // 滑块样式
        show: true,
        xAxisIndex: [0],
        start: 0, // 初始显示的范围
        end: 100,
        height: 12, // 滑块高度，避免过高遮挡
        bottom: '2%', // 滑块距离容器底部的距离
        handleSize: '80%', // 调整滑块手柄大小
        handleIcon: 'M10,10 L90,10 L90,90 L10,90 Z', // 自定义手柄形状
        handleStyle: {
          color: '#888', // 手柄颜色
          shadowBlur: 3,
          shadowColor: '#aaa',
          shadowOffsetX: 2,
          shadowOffsetY: 2,
        },
        textStyle: {
          color: '#666', // 滑块文字颜色
        },
      },
      {
        type: 'inside', // 鼠标滚轮缩放
        xAxisIndex: [0],
        start: 0,
        end: 100,
      },
    ],
  }, true);
};

// 图表自适应
const resizeCharts = () => {
  if (breathStopChartInstance.value) {
    breathStopChartInstance.value.resize();
  }
  if (OXTSChartInstance.value) {
    OXTSChartInstance.value.resize();
  }
};

const disposeChart = () => {
  // 销毁图表实例
  if (breathStopChartInstance.value) {
    breathStopChartInstance.value.dispose();
  }
  if (OXTSChartInstance.value) {
    OXTSChartInstance.value.dispose();
  }
  // 移除事件监听器
  window.removeEventListener('resize', resizeCharts);
};

const editMode = ref(false);
const showEditInput = () => {
  editMode.value = !editMode.value;
};

const currentUserBreathData = ref({
  evaluation: ''
});

const breathStopData = ref({
  count: '1',
  time: '1',
  rate: '1'
});

const slowBreathData = ref({
  count: '1',
  time: '1',
  rate: '1'
});

const ahiValue = ref(0);

const indicatorStyle = computed(() => {
  const ranges = [5, 16, 30]; // 定义每个分段的最大值
  let position = 0;

  if (ahiValue.value < ranges[0]) {
    position = 12.5; // 正常
  } else if (ahiValue.value < ranges[1]) {
    position = 37.5; // 轻度
  } else if (ahiValue.value <= ranges[2]) {
    position = 62.5; // 中度
  } else {
    position = 87.5; // 重度
  }
  console.log(position);
  return {
    position: 'absolute',
    bottom: '10px',
    left: `${position}%`,
    transform: 'translateX(-50%)',
    color: 'black',
    fontSize: '20px',
  };
});
</script>


<style scoped>
.indicator {
  position: absolute;
  bottom: 10px;
  transform: translateX(-50%);
  color: black;
  font-size: 20px;
}
.main-container {
  width: 90%;
  height: 100%;
  background-color: #EFF2F9;
  border-radius: 20px;
}
.content-container {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
}
.title-container {
  width: 100%;
  height: 5%;
  margin-top: 2%;
}
.title-text {
  width: 20%;
  font-size: 18px;
  height: 100%;
  margin-left: 20px;
  align-items: center;
  display: flex;
}
.subtitle-container {
  width: 100%;
  margin-top: 5px;
  margin-bottom: 5px;
}
.subtitle-text {
  font-size: 16px;
  margin-left: 5%;
}
.charts-wrapper {
  width: 100%;
  height: 30%;
  display: flex;
  align-items: center;
  justify-content: center;
}
.chart-container {
  width: 45%;
  height: 100%;
  border-radius: 10px;
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-right: 20px;
}
.chart-background-white {
  background-color: white;
}
.chart-background-f4efeb {
  background-color: #F4EFEB;
}
.chart-content {
  width: 95%;
  height: 95%;
  display: flex;
  flex-direction: column;
}
.ahi-title {
  margin-right: auto;
  margin-top: 10px;
  font-size: 17px;
  font-weight: bolder;
  margin-left: 10px;
}
.indicator-wrapper {
  width: 100%;
  height: 80%;
  display: flex;
  position: relative;
}
.indicator-bar {
  width: 100%;
  height: 40%;
  display: flex;
  margin-top: 40px;
}
.indicator-segment {
  width: 25%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 16px;
}
.normal {
  background-color: #3CB371;
  border-radius: 40px 0 0 40px;
}
.mild {
  background-color: #FDD801;
}
.moderate {
  background-color: #FEA07A;
}
.severe {
  background-color: #FE6347;
  border-radius: 0 40px 40px 0;
}
.ahi-suggestion {
  font-size: 15px;
  margin-bottom: 2px;
  margin-top: auto;
  margin-right: auto;
}
.info-container {
  width: 90%;
  height: 90%;
}
.info-title {
  font-size: 17px;
}
.info-content {
  font-size: 15px;
  font-weight: 300;
}
.chart-large-container {
  width: 90%;
  height: 30%;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: white;
  border-radius: 10px;
}
.chart-large {
  width: 100%;
  height: 100%;
}
.evaluation-wrapper {
  width: 100%;
  height: 15%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-top: 10px;
}
.evaluation-content {
  width: 95%;
  height: 100%;
  display: flex;
  flex-direction: column;
}
.evaluation-header {
  width: 100%;
  height: 30%;
  display: flex;
}
.icon {
  height: 100%;
}
.icon-color {
  color: #3DD986;
  margin-left: 10px;
  margin-right: 10px;
}
.evaluation-title {
  font-size: 17px;
  font-weight: 510;
}
.edit-button {
  height: 100%;
  margin-left: auto;
  background-color: #EFF2F9;
  border: none;
}
.edit-icon {
  color: #3DD986;
  margin-left: 10px;
  margin-right: 10px;
  width: 20px;
  height: 20px;
}
.edit-text {
  font-size: 17px;
  color: #3DD986;
}
.evaluation-body {
  width: 100%;
  height: 50%;
  display: flex;
  flex-direction: column;
  align-items: center;
}
.evaluation-input {
  height: 100%;
  width: 95%;
}
.evaluation-display {
  width: 90%;
  font-size: 15px;
  margin-left: 30px;
  margin-top: 10px;
}

.chart-containerOX {
  width: 90%;
  height: 80%;
  border-radius: 20px;
  background-color: white;
  display: flex;
  flex-direction: column; /* 垂直排列 */
  align-items: center; /* 水平居中 */
  justify-content: space-between; /* 上下分布 */
  /*padding: 10px; !* 内边距 *!*/
}

.stats-container {
  width: 93%;
  height: 20%; /* 统计数据占 20% 高度 */
  display: flex;
  flex-direction: row; /* 水平排列 */
  justify-content: space-around; /* 均匀分布 */
  align-items: center; /* 垂直居中 */
  background-color: white;
  border-radius: 20px;
  padding: 10px;
  gap: 20px;
  /*margin-top: 10px; !* 与血氧时分图的间距 *!*/
}

.stat-item {
  width: 25%; /* 每个统计项均匀分布 */
  text-align: center; /* 文字居中 */
  padding: 10px; /* 内边距 */
  margin: 0 5px; /* 左右间距 */
  border-radius: 10px;
  display: flex;
  flex-direction: column; /* 垂直排列 */
  align-items: center; /* 水平居中 */
  justify-content: center; /* 垂直居中 */
}

.stat-value {
  font-size: 18px;
  font-weight: bold;
}
/* 最低血氧盒子（第一个子元素） */
.stat-item:first-child {
  background-color: #fff4e6;
  border: 1px solid #ff9500; /* 深橙色边框 */
}
/* 最高血氧盒子（第二个子元素） */
.stat-item:nth-child(2) {
  background-color: #e6ffed;
  border: 1px solid #34c759;
}
/* 平均血氧盒子（最后一个子元素） */
.stat-item:last-child {
  background-color: #fff4e6; /* 浅橙色背景 */
  border: 1px solid #ff9500; /* 深橙色边框 */
}
.min-oxygen-value {
  color: #ff9500; /* 文本颜色为橙色 */
}
.max-oxygen-value {
  color: #34c759; /* 文本颜色为橙色 */
}
.avg-oxygen-value{
  color: #ff9500; /* 文本颜色为橙色 */
}


.stat-title {
  font-size: 14px;
  font-weight: bold;
  color: #666;
}
</style>